import React, { Component, PropTypes } from 'react';
import { Form, Icon, Input, Button, Checkbox, message, Radio } from 'antd';
import Md5 from 'js-md5';
import { connect } from 'dva'
import Style from './login.less';
import Service from '../service';

const FormItem = Form.Item;

const formItemLayout = {
  labelCol: { span: 0 },
  wrapperCol: { span: 24 },
};
const VerifLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 6 },
};
const imgLayout = { position: 'absolute', width: '90px', marginLeft: '20px', cursor: 'pointer' };
class ImgElement extends Component {
  constructor(props) {
    super(props);
    this.state = {
      btnText: '获取验证码',
      seconds: 60, //称数初始化
      liked: true //获取验证码文案
    }
  }
  componentWillMount() {
    this.setState({
      keyNum: Math.random()
    });
  }
  handleClick = () => {
    this.setState({
      keyNum: Math.random()
    });
  }

  render() {
    const addr = `${Service.baseUrl}/earlywarn/authCode/authCode?random=${this.state.keyNum}`;
    // const addr = `http://${window.location.host}/earlywarn/authCode/authCode?random=${this.state.keyNum}`;
    return (
      <img src={addr} style={imgLayout} key={this.state.keyNum} onClick={this.handleClick} />

    );
  }
}
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      userMsg: {},
      btnText: '获取验证码',
      seconds: 60, //称数初始化
      liked: true, //获取验证码文案
      userType: 'k'  //默认快递员登录
    }
  }
  handleSubmit = (e) => {
    let self = this;
    e.preventDefault();
    self.props.form.validateFields((err, values) => {
      // console.log('注册')
      if (!err) {
        const params = {
          mobile: values.phone,
          code: values.code,
          // type: 'register',
          zhuce: (data) => {

            if (data) {

              message.success('登陆成功!', 1.5, function () {
                if (self.state.userType == 'k') {
                  localStorage.setItem('token', data.token);
                  localStorage.setItem('account', values.phone);
                  self.context.router.push(`/1/app/kindex`);
                } else {
                  // console.log(11111);
                  localStorage.setItem('token', data.mobile_token);
                  localStorage.setItem('userMDetail', JSON.stringify(data));
                  self.context.router.push(`/2/app/mmy`);
                }
              })
            }
          }
        }

        if (self.state.userType == 'k') {
          self.props.queryUser({ ...params });
        } else {
          self.props.queryMUser({ ...params });
        }

        //this.props.saveUser({ id: '131341313431', user: '蛮王' })
      }
    });
  };


  // 获取验证码
  sendCode = () => {
    var self = this;
    let phone = this.props.form.getFieldValue('phone');
    if (!phone) {
      return message.error('请输入手机号');
    }
    self.setState({
      liked: false
    })
    const params = {
      mobile: phone,
      // type: 'register',
      getCode: (data) => {
        // console.log(data)
        if (data.code == 200) {
          if (data.error == 1002) {
            message.error(data.data.msg);
            self.setState({
              liked: true
            })
          } else {
            self.codepage();
            message.success('您的验证码是：' + data.data);
          }
        } else {
          // console.log(52222)
          self.setState({
            liked: true
          })
          message.error(data.error);
        }
        // message.success('验证码已发送到您的手机');
        // console.log(data);
      }
    }
    if (self.state.userType == 'k') {
      this.props.querySendCode({ ...params });
    } else {
      this.props.queryMSendCode({ ...params });
    }


  }
  codepage = () => {
    let siv = setInterval(() => {
      this.setState({
        liked: false,
        seconds: this.state.seconds - 1,
      }, () => {
        if (this.state.seconds == 0) {
          clearInterval(siv);
          this.setState({
            liked: true,
            seconds: 60
          })
        }
      });
    }, 1000);
  }

  // 单选按钮
  radioFun = (e) => {
    let self = this;
    let v = e.target.value;
    this.setState({
      userType: e.target.value
    })

  }
  // 返回
  returnFun = () => {
    this.context.router.push(`/login`);
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div className={Style.regBoxs}>
        <div className={Style.headWrap}>

          <div className={Style.regTitle}><span className={Style.arrow} onClick={this.returnFun}><Icon type="left" /></span>企业用户登录</div>
        </div>
        <div className={Style.authBoxs}>
          <div className={Style.content}>
            <div className={Style.inputBox}>
              <Form onSubmit={this.handleSubmit} className="login-form">
                <FormItem label='' {...formItemLayout}>
                  {getFieldDecorator('phone', {
                    rules: [{ required: true, message: '请输入手机号码' }]
                  })(
                    <Input placeholder="请输入手机号码" autoComplete="phone" />
                    )}
                </FormItem>

                <FormItem label='' {...formItemLayout} className='codeWrap'>
                  {getFieldDecorator('code', {
                    rules: [{ required: true, message: '请输入验证码' }]
                  })(
                    <Input placeholder="请输入验证码" autoComplete="code" style={{ width: '120px' }} />
                    )}

                  {
                    this.state.liked
                      ?
                      <span className={Style.code} onClick={this.sendCode}> <span>{this.state.btnText}</span></span>
                      :
                      <span className={Style.code} ><span>{this.state.seconds + 's'}</span></span>
                  }

                </FormItem>

                <div className={Style.mb15 + ' ' + "formtype"}>
                  <p className={Style.title}>请选择您的职位</p>
                  <FormItem style={{ textAlign: 'center', borderBottom: 'none' }}>
                    <Radio.Group onChange={this.radioFun} defaultValue="k" buttonStyle="solid">
                      <Radio.Button value="k">快递员</Radio.Button>
                      <Radio.Button value="m">管理员</Radio.Button>

                    </Radio.Group>
                  </FormItem>
                </div>
                <FormItem style={{ textAlign: 'center', marginTop: '30px' }}>
                  <Button type="primary" htmlType="submit">确定</Button>
                  {/* <Button style={{ marginLeft: 20 }} onClick={this.goToLoginFun}>取消</Button> */}
                </FormItem>
                {/* <FormItem style={{ textAlign: 'center' }}>
                  <Button type="primary" htmlType="submit" className="login-form-button" >
                    确&nbsp;&nbsp;定
                    </Button>
                </FormItem> */}
              </Form>
              {/* <p className={Style.goToLogin}>
                <span onClick={this.goToLoginFun}>已注册,前去登陆</span>
              </p> */}
            </div>

          </div>
        </div>


      </div>
    )
  }
}

App.contextTypes = {
  router: React.PropTypes.object
}

function mapStateToProps(state, ownProps) {
  return {
    // userMsg: state.login.userMsg,
    // data: state.login.data.data
  }
}
function dispatchToProps(dispatch) {
  return {
    saveUser(payload, params) {
      dispatch({
        type: 'login/saveUser',
        payload
      })
    },
    queryUser(payload, params) {
      dispatch({
        type: 'login/querykUser',
        payload
      })
    },
    queryMUser(payload, params) {
      dispatch({
        type: 'login/queryMUser',
        payload
      })
    },
    querySendCode(payload, params) {
      dispatch({
        type: 'register/sendKCode',
        payload
      })
    },
    queryMSendCode(payload, params) {
      dispatch({
        type: 'register/sendAdminCode',
        payload
      })
    },
  }
}
export default connect(mapStateToProps, dispatchToProps)(Form.create()(App));
